package com.ittx.dzt.baidu.handler;


import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ittx.dzt.business.PlatformConstant;
import com.ittx.dzt.edi.constant.PlatformMessageConstant;
import com.ittx.dzt.edi.dto.StoreConfigDTO;
import com.ittx.dzt.edi.handler.AbstractBasePlatformApiHandler;
import com.ittx.dzt.edi.vo.ResponseMessageVO;
import com.ittx.dzt.log.monitor.ExceptionLog;
import com.ittx.dzt.mq.core.queue.producer.RocketmqProducer;
import com.ittx.dzt.okhttp.core.HttpRequestTemplate;
import com.ittx.dzt.sys.response.Result;
import com.ittx.dzt.sys.util.SpringUtil;
import com.ittx.dzt.sys.util.json.JacksonTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * 百度平台API处理父类
 * <p>
 *
 * </p>
 *
 * @author wl_code@163.com
 * @version 1.0
 * @date 2025/2/26
 */
@Slf4j
public abstract class AbstractBaseBaiduApiHandler<T> extends AbstractBasePlatformApiHandler<T> {

	@Autowired
	protected RocketmqProducer rocketmqProducer;

	// 取值字段
	public static final String DATA_FIELD = "data";

	@Override
	public String getPlatformCode() {
		return PlatformConstant.BAIDU;
	}

	/**
	 * 执行API请求通用方法
	 *
	 * @param storeConfig 店铺配置
	 * @param paramMap    请求参数
	 * @param requestId   请求id
	 * @return 请求结果
	 */
	public Result<?> executeApi(StoreConfigDTO storeConfig, Map<String, Object> paramMap, String requestId) {
		// 发起请求
		Result result = null;
		try {
			result = fetch(storeConfig, JacksonTool.toJson(paramMap), requestId);
			if (result.isSuccess()) {
				Map<String, Object> resultMap = JacksonTool.toMap(result.getData());
				Map headerMap = MapUtil.get(resultMap, "header", Map.class);
				int code = MapUtil.getInt(headerMap, "succ");
				if (code != 1) {
					String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0003_MSG, requestId, this.getPlatformCode(), this.getBaiduMethod(), result.getData());
					log.error(msg);
					return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0003, msg)).addMsg(JacksonTool.toJson(result));
				}
				return Result.success().addData(resultMap);
			}
			return result;
		} catch (Exception e) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0003_MSG, requestId, this.getPlatformCode(), this.getBaiduMethod(), e.getMessage());
			ExceptionLog.error(e, PlatformMessageConstant.MSG_PLAT_0003_MSG, requestId, this.getPlatformCode(), this.getBaiduMethod(), e.getMessage());
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0003, msg)).addMsg(msg);
		}
	}

	/**
	 * 公共HTTP请求平台API
	 *
	 * @param storeConfig 店铺配置
	 * @param paramJson   请求参数
	 * @param requestId  请求id
	 * @return 请求结果
	 * @throws IOException
	 */
	private Result fetch(StoreConfigDTO storeConfig, String paramJson, String requestId) throws IOException {
		String url = new StringBuffer(storeConfig.getSdkUrl()).append(this.getBaiduMethod()).toString();
		HttpRequestTemplate httpRequestTemplate = SpringUtil.getBean(HttpRequestTemplate.class);
		if (httpRequestTemplate == null) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0006_MSG, HttpRequestTemplate.class.getName());
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0006, msg));
		}
		log.debug("url:{},json:{}", url, paramJson);
		String returnMsg = httpRequestTemplate.postJsonParams(url, paramJson);
		if (StrUtil.isEmpty(returnMsg) || !JSONUtil.isJson(returnMsg)) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0012_MSG, requestId, this.getPlatformCode()
					, this.getBaiduMethod(), url, returnMsg);
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0012, msg));
		}
		return Result.success().addData(returnMsg);
	}


	/**
	 * 获取百度平台方法名称
	 *
	 * @return 百度平台API
	 * @date 2022/5/5 15:01
	 */
	public abstract String getBaiduMethod();

	/**
	 * 获取总页数
	 *
	 * @param totalCount 总记录数
	 * @param pageSize   每页显示记录数
	 * @return 总页数
	 */
	public Integer totalPage(Integer totalCount, Integer pageSize) {
		if (totalCount <= pageSize) {
			return 1;
		}
		if (totalCount % pageSize == 0) {
			return totalCount / pageSize;
		}
		return (totalCount / pageSize) + 1;
	}

	public Long totalPage(Long totalCount, Long pageSize) {
		if (totalCount <= pageSize) {
			return 1L;
		}
		if (totalCount % pageSize == 0) {
			return totalCount / pageSize;
		}
		return (totalCount / pageSize) + 1;
	}

	/**
	 * 时间格式转换
	 */
	public String timeToString(LocalDateTime localDateTime, String format) {
		DateTimeFormatter df = DateTimeFormatter.ofPattern(format).withZone(ZoneOffset.UTC);
		return df.format(localDateTime);
	}

	public String format(LocalDateTime localDateTime, String format) {
		DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
		return df.format(localDateTime);
	}
}
